package com.example.yucheng.controller;

import com.example.yucheng.domain.Stock;
import com.example.yucheng.service.StockService;
import com.example.yucheng.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/stock")
public class StockController {

    @Autowired
    StockService stockService;

    @GetMapping("/getStockList")
    public Result getStockList(@RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize){
        List<Stock> stockList;
        Map<String, Object> map = new HashMap<>();
        if (pageNum == null && pageSize == null) {
            stockList = stockService.getAllGood();
        }else{
            pageNum -= 1;
            pageNum *= pageSize;
            stockList = stockService.getStockList(pageNum, pageSize);
        }
        map.put("stockList", stockList);
        map.put("total", stockService.getAllGood().size());
        return Result.success(map);
    }

    @PutMapping("/updateStock")
    public Result updateStock(@RequestBody Stock stock){
        System.out.println(stock);
        Stock stock2 = stockService.findStock(stock.getName());
        if ( stock.getId() != stock2.getId()){
            return Result.success("修改失败，库存已经存在该商品");
        }
        stockService.updateStock(stock);
        return Result.success("修改成功");
    }

    @DeleteMapping("/deleteStock")
    public Result deleteStock(@RequestParam int [] ids){
        for(int id : ids){
            stockService.deleteStock(id);
        }
        return Result.success("删除成功");
    }

    @PostMapping("/addStock")
    public Result addStock(@RequestBody Stock stock){
        Stock stock2 = stockService.findStock(stock.getName());
        if (stock2 == null) {
            stockService.addStock(stock);
            return Result.success("增加成功");
        }else{
            return Result.success("添加失败，已经有该商品");
        }
    }
}
